<template>
  <up-navbar
      title="物资找寻"
      :autoBack="true"
      bgColor="#4792FD"
      leftIconColor="white"
      rightText="功率"
      @rightClick="handlerShowPower"
      style="color: white;"
      :titleStyle="{ color: '#FFF'}">
  </up-navbar>
  <view class="content-container">
    <view class="card-container">
      <view class="top">
        <span class="title">{{ item.asset_name }}</span>
        <span class="status">{{ item.asset_state_name }}</span>
      </view>
      <view class="content">
        <view class="img">
          <image :src="getImage(item.image)"/>
        </view>
        <view class="info">
          <span>资产编号：{{ item.asset_code }}</span>
          <span>所属部门：{{ item.department_name }}</span>
          <span>存放位置：{{ item.location_name }}</span>
          <span>使用人：{{ item.user_name }}</span>
        </view>
      </view>
      <up-line></up-line>
      <view class="footer">
        <span>RFID：{{ item.label_number }}</span>
      </view>
    </view>
    <view class="number">
      <view>
        <image src="/static/imgs/wifi.png" />
<!--        <img src="/static/imgs/avatar.png"/>-->
        <span>已扫描到：{{count}}次</span>
      </view>
      <u-button style="margin-top: auto;" type="primary" text="开始扫描" @click="handlerStart">{{title}}</u-button>
    </view>
  </view>
  <up-modal
      :show="showPower"
      title="设置功率"
      :closeOnClickOverlay="true"
      @close="showPower = false"
      :showCancelButton="true"
      confirmText="确定"
      cancelText="取消"
      @cancel="showPower = false"
      @confirm="handlerSetPower">
    <view style="width: 100%">
      <span style="font-size: .9rem;margin-bottom: 20rpx;">功率：{{ sliderValue }}</span>
      <up-slider v-if="showPower" v-model="sliderValue" min="5" max="33"></up-slider>
    </view>
  </up-modal>
</template>

<script>

import {BASE_URL} from "@/api/request";

const plugin = uni.requireNativePlugin('RFIDPlugin')

var main, receiver, filter;

export default {
  data() {
    return {
      isStart: false,
      item: {},
      showPower: false,
      sliderValue: 33,
      title: '开始扫描',
      count: 0
    }
  },
  onLoad(options) {
    this.item = JSON.parse(options.item)
  },
  created: function (option) {
    console.log('created');
    //this.initEventListener();
    this.registerReceiver();
  },
  onShow() {
    console.log('onShow');
    // 在这里可以执行亮屏后需要的操作，如重新加载数据等
  },
  onHide: function () {
    console.log('onHide');
    //this.unregisterReceiver();
  },
  onBackPress() {
    console.log('onBackPress');
    plugin.uninitUHFManager();
  },
  destroyed: function () {
    console.log('destroyed');
    this.unregisterReceiver();
  },
  methods: {
    inituhf() {
      let _this = this;
      var result = plugin.initUHFManager();
      console.log(result)
      if (result == 1) {
        console.log("init success")
      } else {
        console.log("init fail")
      }
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      //下面的addAction内改为自己的广播动作
      filter.addAction("com.pda.keycode.broacast"); //按键广播
      filter.addAction("com.rfid.lib.plugin.RFIDPlugin"); //超高频tag广播

      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);

          let m_action = intent.getAction();

          // console.log("action:" + m_action);

          if (m_action == "com.pda.keycode.broacast") { //接收到按键广播，处理按键广播事件
            //下面的getStringExtra内改为自己的广播标签
            let keycode = intent.getIntExtra("keycode", 0);
            let iskeydown = intent.getBooleanExtra("isdown", false);

            if (keycode == 292) { //手柄按键键值292
              if (iskeydown) {
                plugin.startInventory();
                _this.isStart = true
                _this.title = '停止扫描'
              } else {
                plugin.stopInventory();
                _this.isStart = false
                _this.title = '开始扫描'
              }
            }
            // console.log("keycode:" + keycode + ", isdown:" + iskeydown + ", result:" + result)
          } else if (m_action == "com.rfid.lib.plugin.RFIDPlugin") {
            let uhfdata = intent.getStringExtra("data");
            // console.log("TAGS:" + uhfdata);
            if (uhfdata) {
              const data = JSON.parse(uhfdata)
              for (let i = 0; i < data.length; i++) {
                if (data[i].labelNumber === _this.item.label_number) {
                  _this.count = _this.count + 1
                }
              }
            }
          }
        }
      });

    },
    registerReceiver() {
      this.inituhf()
      main.registerReceiver(receiver, filter);
    },
    unregisterReceiver() {
      main.unregisterReceiver(receiver);
      plugin.uninitUHFManager();
    },
    handlerShowPower() {
      this.showPower = true
    },
    handlerStart() {
      if (this.isStart) {
        plugin.stopInventory()
        this.isStart = false
        this.title = '开始扫描'
      } else {
        plugin.startInventory()
        this.isStart = true
        this.title = '停止扫描'
      }
    },
    getImage(image){
      const type = this.getItemType(image);
      if (image) {
        if (type === "ID") {
          return `${BASE_URL}/File/GetImage?fileId=${image}`;
        } else {
          return image;
        }
      }
      return "";
    },
    getItemType(item){
      const idPattern = /^[a-zA-Z0-9-]+$/; // 包含字母、数字和 - 符号
      const apiPattern = /^\/File\//; // 假设接口地址以 '/File/' 开头
      const pathPattern = /^\/(?!File)/; // 普通路径以 '/' 开头，但不以 '/File/' 开头
      const relativePathPattern = /^[^/]/; // 假设相对路径不以 '/' 开头

      if (idPattern.test(item)) {
        return "ID";
      } else if (apiPattern.test(item)) {
        return "接口"; // 识别接口地址
      } else if (pathPattern.test(item)) {
        return "路径"; // 识别普通路径
      } else if (relativePathPattern.test(item)) {
        return "相对路径"; // 识别相对路径
      } else {
        return "其他";
      }
    },
    handlerSetPower() {
      this.showPower = false
      const res = plugin.setPower(this.sliderValue)
      if (res) {
        uni.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        uni.showToast({
          title: '设置失败',
          icon: 'error',
          duration: 2000
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">

.content-container {
  height: calc(100vh - var(--window-top, 0px));
  padding: 160rpx 10rpx 10rpx 10rpx;
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;

  .card-container {
    width: calc(100% - 20rpx);
    height: 380rpx;
    background-color: white;
    border-radius: 10rpx;
    padding: 10rpx;
    margin-bottom: 20rpx;

    .top {
      display: flex;
      flex-direction: row;

      .title {
        font-size: 1.2rem;
        font-weight: bold;
      }

      .status {
        margin-left: auto;
        color: #4692FD;
      }
    }

    .content {
      display: flex;
      flex-direction: row;
      margin: 20rpx 0;

      .img {
        width: 200rpx;
        height: 200rpx;

        > image {
          height: 100%;
          width: 100%;
        }
      }

      .info {
        padding-left: 20rpx;
        display: flex;
        flex-direction: column;

        > span {
          font-size: .9rem;
          color: #858585;
          margin: 5rpx 0;

          &:first-child {
            margin-top: 0;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .footer {
      margin-top: 20rpx;
    }
  }

  .number {
    flex: 1;
    width: calc(100% - 20rpx);
    display: flex;
    flex-direction: column;

    view {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      image {
        height: 450rpx;
        width: 450rpx;
      }

      span {
        font-size: 1.4rem;
        font-weight: bold;
      }
    }
  }
}
</style>